package com.msy.mai.framework.social.core.utils;

import cn.hutool.core.util.ObjectUtil;
import com.msy.mai.common.core.utils.SpringUtils;
import com.msy.mai.framework.social.configuration.properties.SocialLoginConfigProperties;
import com.msy.mai.framework.social.configuration.properties.SocialProperties;
import com.msy.mai.framework.social.core.enums.AuthSource;
import com.msy.mai.framework.social.core.maxkey.AuthMaxKeyRequest;
import com.msy.mai.framework.social.core.topiam.AuthTopIamRequest;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.*;

/**
 * 认证授权工具类
 *
 * @author thiszhc
 */
public class SocialUtils  {

    private static final AuthRedisStateCache STATE_CACHE = SpringUtils.getBean(AuthRedisStateCache.class);

    @SuppressWarnings("unchecked")
    public static AuthResponse<AuthUser> loginAuth(String source, String code, String state, SocialProperties socialProperties) throws AuthException {
        AuthRequest authRequest = getAuthRequest(source, socialProperties);
        AuthCallback callback = new AuthCallback();
        callback.setCode(code);
        callback.setState(state);
        return authRequest.login(callback);
    }

    public static AuthRequest getAuthRequest(String source, SocialProperties socialProperties) throws AuthException {
        SocialLoginConfigProperties obj = socialProperties.getType().get(source);
         if (ObjectUtil.isNull(obj)) {
            throw new AuthException("不支持的第三方登录类型");
        }
        AuthConfig.AuthConfigBuilder builder = AuthConfig.builder()
            .clientId(obj.getClientId())
            .clientSecret(obj.getClientSecret())
            .redirectUri(obj.getRedirectUri())
            .scopes(obj.getScopes());
        switch (AuthSource.of(source.toLowerCase())) {
            case GITHUB :
                return new AuthGithubRequest(builder.build(), STATE_CACHE);
            case GITEE :
                return new AuthGiteeRequest(builder.build(), STATE_CACHE);
            case WECHAT_OPEN :
                return new AuthWeChatOpenRequest(builder.build(), STATE_CACHE);
            case WECHAT_MP :
                return new AuthWeChatMpRequest(builder.build(), STATE_CACHE);
            case MAXKEY :
                return new AuthMaxKeyRequest(builder.build(), STATE_CACHE);
            default :
                 throw new AuthException("未获取到有效的Auth配置");
        }
    }
}

